package com.woniuxy.consumer.student.controller;

import com.woniuxy.common.DTO.ResponseResult;
import com.woniuxy.common.entity.Student;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author: linKe
 * @Date: 2022/1/20 9:48
 * @FileName: EurekaConsumerStudentController
 * @version: 1.0
 * @Description: 改造成eureka注册中心调用服务
 * 
 * 学生消费服务调用类
 * 远程调用8081项目
 *
 * 原始调用方式：RestTemplate调用
 */
@Api(tags = {"消费者","调用方"},value = "调用学生类")
@RestController
@RequestMapping("/eureka/consumerStudent")
public class EurekaConsumerStudentController {

    @Autowired
    RestTemplate restTemplate;
    /**
     * 注册中心服务 调用端
     */
    @Autowired
    DiscoveryClient discoveryClient;
    
    final String URL = "HTTP://localhost:8081/student/";

//    String getUrl(){
//        List<ServiceInstance> instances = discoveryClient.getInstances("provider-student");
//        ServiceInstance serviceInstance = instances.get(0);
//        // 替换成eureka 获取url地址
//        return "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/student/";
//    }

    /**
     * 使用ribbon 调用
     * @return  url地址
     */
    String getUrl(){
        // Ribbon 的本质就是restTemplate+@LoadBalenced
      return "http://provider-student/student/";

    }
    
    
    @GetMapping("/{id}")
    public ResponseResult<Student> getStudentById(@PathVariable("id")int id) {
        // restTemplate的API 实现远程调用
        return restTemplate.getForObject(getUrl()+id, ResponseResult.class);
    }

    @GetMapping("/")
    public ResponseResult<List<Student>> getStudentAll() {
        // restTemplate的API 实现远程调用
        return restTemplate.getForObject(getUrl(), ResponseResult.class);
    }

    @PostMapping("/")
    public ResponseResult<List<Student>> addStudent(@RequestBody Student student) {
        // restTemplate的API 实现远程调用
        return restTemplate.postForObject(getUrl(),student, ResponseResult.class);
    }

    @ApiOperation("分页查询")
    @GetMapping("/{pageIndex}/{pageSize}")
    public ResponseResult<List<Student>> getStudentPage(@PathVariable("pageIndex") int pageIndex,
                                                        @PathVariable("pageSize") int pageSize,
                                                        @RequestBody Student student) {
        // restTemplate的API 实现远程调用
        return restTemplate.getForObject(getUrl(), ResponseResult.class);
    }
}
